﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using FineUI;
using SysManage.BLL;
using ZHDJ.Data.Models.Common;
using ZHDJ.Data.Models.Grassroots;

namespace SysManage.Module.Grassroots
{
    public partial class GroupList : PageBase
    {
        #region ViewPower

        /// <summary>
        /// 本页面的浏览权限，空字符串表示本页面不受权限控制
        /// </summary>
        public override string ViewPower
        {
            get
            {
                return "GrassrootsGroupView";
            }
        }

        #endregion

        #region Page_Load

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                hdSelectrowindex.Text = "0";
                if (!IsSystemAdmin)
                {
                    Region1.Hidden = true;
                    this.btnNew.Hidden = true;
                    this.btnDeleteSelected.Hidden = true;
                    btnChangeEnableUsers.Hidden = true;
                    Grid2.Columns[Grid2.Columns.Count-1].Hidden = true;
                }
                LoadData();
            }

        }

        private void LoadData()
        {
            // 权限检查
            CheckPowerWithButton("GrassrootsGroupAdd", btnNew);
            CheckPowerWithButton("GrassrootsGroupDelete", btnDeleteSelected);
            
            BindGrid1();




            btnModule.OnClientClick = WindowModule.GetShowReference("GroupEdit.aspx");
            // 每页记录数
            Grid2.PageSize = ConfigHelper.PageSize;
            ddlGridPageSize.SelectedValue = ConfigHelper.PageSize.ToString();
            BindGrid2();
        }

        private void BindGrid1()
        {
            var ds = PartyGrassrootsGroup.GetGridData(Grid1.PageIndex, Grid1.PageSize);

            Grid1.RecordCount = Convert.ToInt32(ds.Tables[1].Rows[0][0]);
            Grid1.DataSource = ds.Tables[0];
            Grid1.DataBind();
            if (string.IsNullOrEmpty(this.hdModule.Text))
            {
                hdSelectrowindex.Text = "0";
                // 默认选中第一个
                Grid1.SelectedRowIndex = 0;
                this.hdModule.Text = GetSelectedDataKeyID(Grid1);
            }
            else
            {
                SetSelectedDataKeyIDs(Grid1, this.hdModule.Text);
                hdSelectrowindex.Text = Grid1.SelectedRowIndex.ToString();
            }
            PageContext.RegisterStartupScript("addSelectCss(" + this.hdSelectrowindex.Text + ")");

        }

        private void BindGrid2()
        {
            string groupId = hdModule.Text;

            if (!IsSystemAdmin)
            {
                var ds = PartyGrassrootsGroupItem.GetGridData(Grid2.PageIndex, Grid2.PageSize, "",
                        txtTitle.Text, BranchID);

                Grid2.RecordCount = Convert.ToInt32(ds.Tables[1].Rows[0][0]);
                Grid2.DataSource = ds.Tables[0];
                Grid2.DataBind();
            }
            else
            {
                if (string.IsNullOrEmpty(hdModule.Text))
                {
                    Grid2.RecordCount = 0;

                    Grid2.DataSource = null;
                    Grid2.DataBind();
                }
                else
                {
                    btnNew.OnClientClick = Window1.GetShowReference("ItemEdit.aspx?GroupID=" + groupId, "新增");

                    var ds = PartyGrassrootsGroupItem.GetGridData(Grid2.PageIndex, Grid2.PageSize, groupId,
                        txtTitle.Text);

                    Grid2.RecordCount = Convert.ToInt32(ds.Tables[1].Rows[0][0]);
                    Grid2.DataSource = ds.Tables[0];
                    Grid2.DataBind();
                }
            }

        }


        #endregion

        #region Events

        protected void ddlGridPageSize_SelectedIndexChanged(object sender, EventArgs e)
        {
            Grid2.PageSize = Convert.ToInt32(ddlGridPageSize.SelectedValue);

            BindGrid2();
        }


        #endregion

        #region Grid1 Events

        protected void Grid1_Sort(object sender, GridSortEventArgs e)
        {
            Grid1.SortDirection = e.SortDirection;
            Grid1.SortField = e.SortField;
            BindGrid1();

            // 默认选中第一个职称
            Grid1.SelectedRowIndex = 0;

            BindGrid2();
        }

        protected void Grid1_RowClick(object sender, FineUI.GridRowClickEventArgs e)
        {
            string groupId = GetSelectedDataKeyID(Grid1);
            this.hdModule.Text = groupId;

            this.hdSelectrowindex.Text = Grid1.SelectedRowIndex.ToString();
            PageContext.RegisterStartupScript("addSelectCss(" + this.hdSelectrowindex.Text + ")");
            btnNew.OnClientClick = Window1.GetShowReference("ItemEdit.aspx?GroupID=" + groupId,"新增小组");
            BindGrid2();



        }

        #endregion

        #region Grid2 Events
        

        protected void Grid2_PreDataBound(object sender, EventArgs e)
        {
            // 数据绑定之前，进行权限检查
            CheckPowerWithLinkButtonField("GrassrootsGroupDelete", Grid2, "deleteField");
            CheckPowerWithLinkButtonField("GrassrootsGroupEdit", Grid2, "editField2");
            CheckPowerWithLinkButtonField("GrassrootsGroupEdit", Grid2, "editField3");
           
        }

        protected void Grid2_Sort(object sender, GridSortEventArgs e)
        {
            Grid2.SortDirection = e.SortDirection;
            Grid2.SortField = e.SortField;
            BindGrid2();
        }

        protected void Grid2_PageIndexChange(object sender, GridPageEventArgs e)
        {
            Grid2.PageIndex = e.NewPageIndex;
            BindGrid2();
        }

        protected void btnDeleteSelected_Click(object sender, EventArgs e)
        {
            // 在操作之前进行权限检查
            if (!CheckPower("GrassrootsGroupDelete"))
            {
                CheckPowerFailWithAlert();
                return;
            }

            List<string> ids = GetSelectedDataKeyIDs(Grid2);
            DB.PartyGrassrootsGroupItems.Where(u => ids.Contains(u.ID)).ToList().ForEach(u => DB.PartyGrassrootsGroupItems.Remove(u));
            DB.SaveChanges();

            // 清空当前选中的项
            Grid2.SelectedRowIndexArray = null;

            // 重新绑定表格
            BindGrid2();
        }


        protected void Grid2_RowCommand(object sender, GridCommandEventArgs e)
        {
            object[] values = Grid2.DataKeys[e.RowIndex];
            string ID = Convert.ToString(values[0]);

            if (e.CommandName == "Delete")
            {
                var del = DB.PartyGrassrootsGroupItems.FirstOrDefault(t => t.ID == ID);
                DB.PartyGrassrootsGroupItems.Remove(del);
                DB.SaveChanges();
                BindGrid2();

            }
        }

        protected void Grid1_RowCommand(object sender, GridCommandEventArgs e)
        {
            object[] values = Grid1.DataKeys[e.RowIndex];
            string ID = Convert.ToString(values[0]);

            if (e.CommandName == "Delete")
            {
                var del = DB.PartyGrassrootsGroups.FirstOrDefault(t => t.ID == ID);
                DB.PartyGrassrootsGroups.Remove(del);
                DB.SaveChanges();
                LoadData();

            }
        }
        /// <summary>
        /// 设置启用
        /// </summary>
        /// <param name="enabled"></param>
        private void SetSelectedEnableStatus(bool enabled)
        {
            // 在操作之前进行权限检查
            if (!CheckPower("GrassrootsGroupEdit"))
            {
                CheckPowerFailWithAlert();
                return;
            }

            // 从每个选中的行中获取ID（在Grid1中定义的DataKeyNames）
            List<string> ids = GetSelectedDataKeyIDs(Grid2);

            // 执行数据库操作
            DB.PartyGrassrootsGroupItems.Where(u => ids.Contains(u.ID)).ToList().ForEach(u => u.State = (enabled?4:1));
            DB.SaveChanges();
            //DB.Users.Update(u => ids.Contains(u.ID), u => new User { Enabled = enabled });

            // 重新绑定表格
            BindGrid2();
        }
        protected void btnEnable_Click(object sender, EventArgs e)
        {
            SetSelectedEnableStatus(true);
        }

        protected void btnDisable_Click(object sender, EventArgs e)
        {
            SetSelectedEnableStatus(false);
        }

        protected void Window1_Close(object sender, EventArgs e)
        {

            BindGrid2();
        }
        protected void Window2_Close(object sender, WindowCloseEventArgs e)
        {
            //this.hdModule.Text = "";
            BindGrid1();

            BindGrid2();

        }

        protected void rblEnableStatus_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindGrid2();
        }

        #endregion

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            BindGrid2();
        }
    }
}
